package com.onpositive.collections;

import java.util.ArrayList;
import java.util.List;

import com.onpositive.data.units.Unit;
import com.onpositive.units.ParsedDimension;

public class CounterValueCalculator implements IMemberValueCalculator {
	
	private static final long serialVersionUID = -3822920669059849178L;

	@Override
	public Object calculateValue(IObjectCollection collection,ICollectionMember<?> member) {
		
		ArrayList<ParsedDimension> lst = new ArrayList<ParsedDimension>() ;
		List<ICollectionDelta<?>> history = collection.getCompleteHistory();
		int size = history.size() ;		
		for( int i = size ; i > 0 ; i-- ){
			ICollectionDelta<?> delta = history.get(i-1);			
			Object value = delta.getValue(member);
			if( !(value instanceof CounterModificator))
				continue ;
			
			CounterModificator cm = (CounterModificator) value ;
			ParsedDimension pDim = cm.getDim();
			lst.add(pDim) ;
			int code = cm.instructionCode ;
			if( code == CounterModificator.INSTRUCTION_CODE_SET )
				break ;
		}
		if( lst.isEmpty() )
			return null ;
		
		double sum = 0 ;
		for( ParsedDimension pDim : lst ){
			
			Double ub = pDim.getUpperBound();
			if( ub == null )
				continue ;
			
			sum += ub ;
		}
		Unit primaryUnit = lst.iterator().next().getUnit().getPrimaryUnit();
		ParsedDimension result = new ParsedDimension(sum, primaryUnit, collection.getName() + " couner value") ;
		return result ;
	}

}
